from rest_framework import serializers
import re
from users.models import User


class RegisterSerializer(serializers.ModelSerializer):
    """注册模型类序列化器"""

    class Meta:
        model = User
        fields = ('username', 'password')
        extra_kwargs = {
            'username': {'min_length': 5, 'max_length': 20}
        }

    def validate_password(self, value):
        """验证密码：必须6到12位，且不能出现空格"""
        ret = re.match('^[\\S]{6,12}$', value)
        if ret is None:
            raise serializers.ValidationError('密码不符合规范！')
        return value

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user
